// 1. 数据模拟 （ 分页接口）
import { FC, useEffect, useRef, useState } from 'react'
import styled from 'styled-components'

const PullContainer = styled.div`
	width: 100vw;
	height: 100vh;
	display: flex;
	flex-direction: column;
	.main {
		flex: 1;
		overflow: auto;
	}
	.loading {
		height: 0.8rem;
		background: lightblue;
		display: flex;
		justify-content: center;
		align-items: center;
	}
`

export const PullUpload: FC = () => {
	const [list, setList] = useState<any[]>([])
	const [page, setPage] = useState<number>(1)
	const [loading, setLoading] = useState<boolean>(false)
	const loadingRef = useRef<HTMLDivElement | null>(null)

	useEffect(() => {
		getData({})
	}, [])

	// 通过useEffect的监听 解决set函数的异步问题
	useEffect(() => {
		if (loading) {
			createData({ page: 1 }).then((res: any) => {
				console.log('data:', res)
				setLoading(false)
				console.log('loading...', loading)
				setList([...list, ...res])
			})
		} else {
		}
	}, [loading])

	useEffect(() => {
		// 监听loading
		handleObserver()
	}, [list])

	useEffect(() => {
		getData({ page: page })
	}, [page])

	const getData = async ({ page = 1, size = 5 }: any) => {
		setLoading(true)
	}

	const handleObserver = () => {
		// 回调函数 监听 - 取消监听
		const callback = (entries: any) => {
			// console.log('entries[0].intersectionRatio:', entries[0].intersectionRatio)
			// if (entries[0].intersectionRatio <= 0) return
			if (!loading && entries[0].isIntersecting) {
				console.log('进入视图：', entries[0].isIntersecting)
				// this.pageOpt.page++
				setPage((page) => page + 1)
				// 请求下一次数据
			}
		}

		const io = new IntersectionObserver(callback, {
			threshold: [1]
		})

		// 开始观察
		if (loadingRef.current) {
			io.observe(loadingRef.current)
		}

		// // 停止观察
		// io.unobserve(boxRef.value)
		// // 关闭观察器
		// io.disconnect()
	}

	return (
		<PullContainer>
			<div className="main">
				{list.map((item) => {
					return (
						<ul key={item.id}>
							<li>
								<img src={item.avatar} alt="" />
							</li>
							<li>{item.name}</li>
						</ul>
					)
				})}
				<div ref={loadingRef} className="loading">
					loading...
				</div>
			</div>
		</PullContainer>
	)
}

export default PullUpload

function createData({ page = 1, size = 5 }: any) {
	let arr: any[] = []
	return new Promise((resolve, reject) => {
		for (let i = 0; i < 1000; i++) {
			arr.push({
				id: i + 1,
				name: `city: ${i + 1} week`,
				avatar: `https://www.robohash.org/${i}`
			})
		}
		setTimeout(() => {
			resolve(arr.slice((page - 1) * size, page * size))
		}, 500)
	})
}
